package com.example.auth.service.impl;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;

import com.example.auth.response.Result;
import com.example.auth.service.LoginService;
import com.example.auth.util.EmailUtils;
import com.example.auth.util.ThreadPoolUtils;
import darabonba.core.client.ClientOverrideConfiguration;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    EmailUtils emailUtils;

    @Resource
    RedisTemplate<String,String> redisTemplate;

    @Override
    public Result sendSms(String phone, String type) throws ExecutionException, InterruptedException {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5tQF6Y9QvdQLoo588czh")
                .accessKeySecret("9U1V3qpcGXjUyc3CvfPTYNpKTl7sLU")
                .build());

        AsyncClient client = AsyncClient.builder()
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride("dysmsapi.aliyuncs.com")
                )
                .build();

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phone)
                .signName("demoIM")
                .templateCode("SMS_463602214")
                .templateParam("{\"code\":\""+code+"\"}")
                .build();

        client.sendSms(sendSmsRequest);
        redisTemplate.opsForValue().set(phone+":"+type+":"+code,"1",5, TimeUnit.MINUTES);
        //阿里云向此手机号发送短信
        return Result.OK("发送成功");
    }

    @Override
    public Result sendEmail(String email, String type) {
        Random random = new Random();
        int code = 100000 + random.nextInt(900000);
        ThreadPoolUtils.threadPoolExecutor.execute(()->{
            emailUtils.sendText("登录验证码",String.valueOf(code),"1305711389@qq.com","122985911@qq.com");
        });
        redisTemplate.opsForValue().set(email+":"+type+":"+code,"1",5, TimeUnit.MINUTES);

        return Result.OK(code);
    }
}
